package com.cj.webapp.account.controller;

import com.cj.webapp.account.pojo.ConstantParamter;
import com.cj.webapp.common.sign.SignVerifyHandle;
import com.cj.webapp.common.utils.HFJsonUtil;
import com.cj.webapp.common.utils.MapDetail;
import com.cj.webapp.common.utils.http.HttpsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 投资使用营销券校验
 * Created by dell on 2017/12/25.
 */

public class MarketTicketUseServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(MarketTicketUseServlet.class);
    private static SignVerifyHandle signVerifyHandle=new SignVerifyHandle();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        String requestJson =sb.toString();
        Map<String, String> jsonToMap = HFJsonUtil.getJsonToMap(requestJson);

        String head = jsonToMap.get("head");
        String body=jsonToMap.get("body");
        logger.info("投资使用营销券校验通知返回报文信息："+head +body);
        try {
            Map<String, String> headMap = HFJsonUtil.getJsonToMap(head);
            Map<String,String> mapRes=new HashMap<>();
                if(signVerifyHandle.verifySign(ConstantParamter.VIP_NUM,body, headMap.get("signData"))){
                    mapRes= HFJsonUtil.getJsonToMap(body);
                    mapRes.put("source", MapDetail.resMap.get("source").toString());

                    HttpsUtil httpsUtil=new HttpsUtil();
                    String jsonString=httpsUtil.sendMarketTicketUsing(mapRes,ConstantParamter.DIRECT_WAY_URL);
                    response.getWriter().write(jsonString);
                    logger.info("投资使用营销券校验跳转到成功");

                }else{
                    logger.info("投资使用营销券校验:验签失败");
                }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("对不起，报错啦！！接收的数据"+head+body);
        }

    }
}
